package com.wanmait.wisdom.interceptor.web;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wanmait.wisdom.entity.Resident;
import com.wanmait.wisdom.util.JWTUtils;
import com.wanmait.wisdom.util.web.WebJWTUtils;
import com.wanmait.wisdom.web.service.WebResidentService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class WebJWTInterceptor implements HandlerInterceptor {
//    @Resource
//    private AdminService adminService;

    @Resource
    private WebResidentService webResidentService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //预检请求放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        if (request.getRequestURI().contains("/login") ||request.getRequestURI().contains("/home")) {
            return true;
        }
        if (request.getRequestURI().contains("/manage")){
            return true;
        }
        //获得token
        String webToken = request.getHeader("webToken");
        if (webToken == null) {
            throw new JWTVerificationException("没有携带token");
        }

        //获得签发对象
        Integer id = null;
        try {
            id = Integer.parseInt(JWTUtils.getAudience(webToken));
            System.out.println(id);
        } catch (NumberFormatException e) {
            throw new JWTVerificationException("解析token获得签发对象失败");
        }

        //查询admin
//        Admin admin = adminService.findById(id);
//        if(admin==null){
//            throw new JWTVerificationException("没有查询到用户");
//        }
//        JWTUtils.verifyToken(token,admin.getPassword());
//
//        request.setAttribute("admin",admin);

        //查询resident
        Resident resident = webResidentService.findById(id);
        if (resident == null) {
            throw new JWTVerificationException("没有查询到用户");
        }
        WebJWTUtils.verifyToken(webToken, resident.getPassword());

        request.setAttribute("resident", resident);

        return true;
    }
}
